package com.bsj.power.pls.config.net.netty.protocol;

import com.bsj.power.common.def.protocol.uwb.DataUwbInfo;
import com.bsj.power.pls.config.net.netty.AnalysisData;
import com.bsj.tools.HexStr;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description uwb协议解析
 * @date 2024/9/23
 */
@Slf4j
public class UWBActuator implements AnalysisData {

    /**
     * 分包
     * @param in
     * @param out
     * @throws Exception
     */
    @Override
    public void decode(ByteBuf in, List<Object> out) throws Exception {
        // 该方法返回ByteBuf有多少字节可以读
        int len = in.readableBytes();
        // 转为数组
        byte[] data = new byte[len];

        // ByteBuf getBytes(in.readerIndex(),data)
        // 将这个缓冲区的数据转移到指定的目的地从指定的绝对索引开始
        // 这个方法不会修改buffer读索引（readerIndex）或者写索引（writerIndex）
        // int readerIndex()方法返回buffer的读索引
        in.getBytes(in.readerIndex(), data);
        // 存放正确包的集合
        List<Object> okList = new ArrayList<>(10);
        // 将数据分成有效的数据包，返回缓冲区中剩余有效数据的索引
        int lastOkIndex = UWBPacket.packet(okList, data);
        in.readBytes(lastOkIndex).release();
        out.addAll(okList);
        int unLen = len - lastOkIndex;
        if(unLen == 0){
            in.readBytes(in.readableBytes()).release();
            return;
        }
        if (unLen == 1) {
            return;
        }
        //找包头
        int posHead = UWBPacketUtil.getPosHead(data, lastOkIndex);
        if (posHead < 0 && lastOkIndex < len) {
            byte[] arr = new byte[unLen];
            System.arraycopy(data, lastOkIndex, arr, 0, unLen);
            log.info("[UWB24]错误数据： {}", HexStr.toStr(arr));
            in.readBytes(in.readableBytes()).release();
            return;
        }
        if (len - posHead < 5) {
            return;
        }
        if (unLen > 0 && unLen < 2048) {
            return;
        } else {
            try {
                byte[] arr = new byte[unLen];
                System.arraycopy(data, posHead, arr, 0, unLen);
                in.readBytes(in.readableBytes()).release();
                return;
            } catch (Exception e) {
                log.error("[UWB24]数据有问题: {}", posHead + "/" + lastOkIndex);
                log.error("[UWB24]原始有问题的数据为: {}", HexStr.toStr(data));
                return;
            }

        }
    }

    /**
     * 解析
     * @param bytes
     * @return
     * @throws Exception
     */
    @Override
    public DataUwbInfo analysis(byte[] bytes) throws Exception {
        UWBPacket.parser(bytes);
        return null;
    }
}
